﻿using System;
namespace IFramework
{
    public class StateTransition : IStateTransition
    {
        private StateTransitionType transitionType;
        private IFSMState headState;
        private IFSMState trailState;
        private Func<bool> conditionHandle;
        public StateTransitionType TransitionType { get { return transitionType; }set { transitionType = value; } }
        public IFSMState HeadState { get { return headState; } }
        public IFSMState TrailState { get { return trailState; } }
        public Func<bool> ConditionHandle { get { return conditionHandle; } }
        public bool IsMetCondition { get { return RunConditions(); } }

        public StateTransition(StateTransitionType transitionType)
        {
            this.transitionType = transitionType;
        }

        public void SetHeadState(IFSMState state)
        {
            if (state==null) throw new Exception("State is " + state);
            this.headState = state;
        }
        public void SetTrailState(IFSMState state)
        {
            if (state == null) throw new Exception("State is " + state);
            this.trailState = state;
        }

        public void BindCondition(ITransitionCondtion condtion)
        {
            Func<bool> func = condtion.IsMetCondition;
            if (func == null) throw new Exception("Func is" + func);
            conditionHandle += func;
        }
        public void BindCustomCondition(Func<bool> condtion)
        {
            if (condtion == null) throw new Exception("Func is" + condtion);
            conditionHandle += condtion;
        }

        public IFSMState GoToNextState()
        {
            headState.OnExit();
            if (trailState==null) throw new Exception("TrailState is Null");
            trailState.OnEnter();
            return trailState;
        }

     
        private bool RunConditions()
        {
            if (conditionHandle == null) return false;
            Delegate[] conditions = conditionHandle.GetInvocationList();    //获取所有委托
            bool finalReslt = true;
            for (int i = 0; i < conditions.Length; i++)                    //全跑一遍，得到结果
            {
                var result = (Func<bool>)conditions[i];
                finalReslt = finalReslt && result();                
            }
            return finalReslt;
        }
    }
}